<script setup lang='ts'>
import type { VxeGridProps } from 'vxe-table'

import { useGetCategoryTree } from '@fl/api/mall-api'
import { getBoundCategoty } from '@fl/api/man-api'
import { SearchTable, SubmitBtn } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

const emits = defineEmits(['selectDataChange'])
const tableRef = ref()
const selectData = ref<any[]>([])
const { createMessage } = useMessage()
const boundVisible = defineModel<boolean>('boundVisible', { required: true })
const records = ref()
const defaultProps = {
    children: 'children',
    label: 'categoryName',
}

const gridOptions = reactive<VxeGridProps>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'id', title: '类目ID' },
        { field: 'categoryName', title: '类目名称' },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 500,
    keepSource: true,
    showOverflow: true,
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

const { data: treeData, isLoading } = useGetCategoryTree()

const isPending = computed(() => {
    return false
})

function checkChildrenData(data) {
    if (!data || !data.length) {
        return data // 若数据为空或不存在，则直接返回
    }

    for (let i = 0; i < data.length; i++) {
        if (data[i].children && data[i].children.length > 0) {
            return [] // 如果有嵌套的children数据，则返回空数组
        }
    }

    return data // 如果没有嵌套的children数据，则返回当前对象的children数据
}

function handleNodeClick(node: any) {
    records.value = cloneDeep(checkChildrenData(node?.children))
}

function cancel() {
    boundVisible.value = false
}

function reset() {
    boundVisible.value = false
}

async function confirm() {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        const selectRecords = $table.getCheckboxRecords()
        if (!selectRecords.length) {
            createMessage.warning('请至少选择一条数据')
            return
        }
        selectData.value = selectRecords.map((item) => {
            return {
                categoryName: item.categoryName,
                categoryPath: item.categoryPath,
                categorySort: item.categorySort,
                id: item.id,
                isHidden: item.isHidden,
                parentId: item.parentId,
            }
        })
        if (selectData.value.length > 0) {
            const res = await getBoundCategoty({ categoryIds: selectData.value.map(item => item.id).join(',') })
            emits('selectDataChange', res)
        }
        boundVisible.value = false
        $table.clearCheckboxRow()
    }
}
</script>

<template>
    <PlusDialog v-model="boundVisible"
                title="绑定后台类目"
                width="1200"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <div class="category-wrap">
            <div class="left">
                <div class="tree-wrap">
                    <el-tree :data="treeData"
                             class="py-10 pl-10 pr-15"
                             node-key="id"
                             highlight-current
                             default-expand-all
                             :props="defaultProps"
                             :expand-on-click-node="false"
                             @node-click="handleNodeClick"
                    />
                </div>
            </div>

            <div class="right">
                <div class="p-10">
                    <SearchTable ref="tableRef"
                                 v-bind="gridOptions"
                                 row-class-name="table-row-style"
                                 :loading="isLoading"
                                 :data="records"
                    />
                </div>
            </div>
        </div>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>

<style scoped lang='less'>
.category-wrap {
    width: 100%;
    height: 500px;
    display: flex;
    overflow: hidden;
    background: #f5f6fa;
    border: 1px solid #dcdfe6;
    .left {
        width: max-content;
        min-width: 288px;
        margin-right: 10px;
        background-color: #fff;
        overflow: hidden;
        .tree-wrap {
            width: 100%;
            height: 500px;
            overflow-y: auto;
        }
    }

    .right {
        flex: 1;
        background-color: #fff;
        overflow: hidden;
    }
}
</style>
